package org.linlinjava.litemall.db.service;

import org.linlinjava.litemall.db.dao.LitemallCustomerMapper;
import org.linlinjava.litemall.db.domain.LitemallCustomer;
import org.linlinjava.litemall.db.domain.LitemallCustomerExample;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class LitemallCustomerService {
    @Resource
    LitemallCustomerMapper dao;

    public void  insert(LitemallCustomer customer) {
        customer.setRegistrationDate(new SimpleDateFormat("yyyy/MM/dd").format(new Date()));
        dao.insertSelective(customer);
    }

    public LitemallCustomer getUser(Long id, String oldPassword) {
        LitemallCustomer customer = dao.selectByPrimaryKey(id);
        return customer.getUserPassword().equals(oldPassword) ? customer : null;
    }
    //用户Long 唯一ID..得到用户信息
    public LitemallCustomer getUser(Long id) {
        LitemallCustomer customer = dao.selectByPrimaryKey(id);
        customer.setUserPassword(null);
        return customer;
    }
    //用户String唯一ID..得到用户信息
    public LitemallCustomer getUser(String accountId) {
        LitemallCustomerExample example = new LitemallCustomerExample();
        example.or().andAccountIdEqualTo(accountId);
        return dao.selectOneByExample(example);
    }

    public List<LitemallCustomer> queryByInvitation(String invitation) {
        LitemallCustomerExample example = new LitemallCustomerExample();
        example.or().andInvitationEqualTo(invitation);
        return dao.selectByExample(example);
    }

    public void update(LitemallCustomer customer) {
        dao.updateByPrimaryKeySelective(customer);
    }

    public void updateNull(LitemallCustomer customer) {
        dao.updateByPrimaryKey(customer);
    }

    public List<LitemallCustomer> query (String condition) {
        LitemallCustomerExample example = new LitemallCustomerExample();
        condition = condition == null ? "%" : "%" + condition +"%";
        example.or().andAccountIdLike(condition);
        example.or().andMailLike(condition);
        example.or().andNicknameLike(condition);
        example.or().andUsernameLike(condition);
        return dao.selectByExampleSelective(example, LitemallCustomer.Column.excludes(LitemallCustomer.Column.userPassword));
    }

    public List<LitemallCustomer> queryPhone (String condition) {
        LitemallCustomerExample example = new LitemallCustomerExample();
        condition = condition == null ? "%" : "%" + condition +"%";
        example.or().andPhoneLike(condition);
        return dao.selectByExample(example);
    }

    //根据用户名查找
    public List<LitemallCustomer> findByName(String customerName){
        LitemallCustomerExample example = new LitemallCustomerExample();
        example.or().andUsernameLike("%"+customerName+"%").andIsDeletedEqualTo(false);
        return dao.selectByExampleSelective(example);
    }

}
